package com.zheng.study.web.controller.main.company;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.zheng.study.base.bean.BaseEnumManager;
import com.zheng.study.base.bean.Result;
import com.zheng.study.base.bean.SystemConfig;
import com.zheng.study.base.bean.search.SearchEnum;
import com.zheng.study.base.bean.search.order.Order;
import com.zheng.study.base.bean.search.result.SearchResultPaging;
import com.zheng.study.base.bean.search.rule.Rule;
import com.zheng.study.base.bean.search.rule.RuleHelper;
import com.zheng.study.company.entity.Admin;
import com.zheng.study.company.entity.Duty;
import com.zheng.study.company.entity.Power;
import com.zheng.study.company.entity.User;
import com.zheng.study.company.service.AdminService;
import com.zheng.study.company.service.UserService;
import com.zheng.study.web.controller.BaseController;
import com.zheng.study.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成员信息
 * ============================================================================
 * author : dzw
 * createDate:  2018/8/23 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/member")
public class MemberController extends BaseController {
	private static final long serialVersionUID = -2616404086877660604L;

	@Autowired
	private UserService userService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private SystemConfig systemConfig;

	@RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public  Map<String, Object> list(@CurrentUser User user, Integer draw){
		Order order = Order.order("pinYinHead", SearchEnum.OrderType.asc);
		List<Rule> rules = new ArrayList<Rule>();
		rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));
		rules.add(RuleHelper.eq("company", user.getCompany()));
		SearchResultPaging searchResult = userService.findPagingBySearch(null, rules, order);
		List<User> userList = searchResult.getList();

		List<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> rMap;
		for(User member : userList){
			rMap = new HashMap<String, Object>();
			rMap.put("id", member.getId());
			rMap.put("name", member.getName());
			rMap.put("sex", member.getSex()!=null ? member.getSex().name() : "");
			rMap.put("account", adminService.getAccount(member));

			Admin admin = adminService.get(member.getAdminId());
			rMap.put("accountType", "");
			rMap.put("accountEnabled", 0);
			if(admin!=null){
				rMap.put("accountType", admin.getAccountTypeEnum().name());
				rMap.put("accountEnabled", admin.getAccountEnabled()!=null ? admin.getAccountEnabled() : 0);
			}
			dataRows.add(rMap);
		}

		for(int i=0;i<120;i++){
			rMap = new HashMap<String, Object>();
			rMap.put("id", "000"+i);
			rMap.put("name", "用户"+i);
			rMap.put("account", "000"+i);
			rMap.put("sex", "男");
			rMap.put("accountType", "User");
			rMap.put("accountEnabled", 0);
			dataRows.add(rMap);
		}

		data.put("data", dataRows);
		data.put("draw", draw);
		data.put("recordsTotal", searchResult.getTotalCount());
		data.put("recordsFiltered", searchResult.getTotalCount());
		return data;
	}

	/**
	 * 新建dialog
	 */
	@RequestMapping(value = "input", method = RequestMethod.GET)
	public String input(){
		return "main/company/member_input";
	}

	/**
	 * 验证登录账号是否可用
	 */
	@RequestMapping(value = "checkAccount", method = RequestMethod.POST)
	@ResponseBody
	public Object checkAccount(String account){
		Admin admin = adminService.getAdminByAccount(account);
		if(admin==null){
			return ajaxJson("true");
		}else{
			return ajaxJson("false");
		}
	}

	/**
	 * 创建新账号
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public Object create(@CurrentUser User user,  String username, String account, String password){
		Result result = userService.createMember(account, password, username, user.getCompany());
		return ajaxJson(result);
	}

	/**
	 * 职责信息dialog
	 */
	@RequestMapping(value = "dutyDialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
	public String dutyDialog(Model model, String userId){
		model.addAttribute("userId", userId);
		User user = userService.get(userId);
		if(user!=null){
			List<Duty> dutyList = dutyService.getUserDutyList(user);
			List<Map<String, Object>> dutyData = new ArrayList<Map<String, Object>>();
			Map<String, Object> rMap;
			for(Duty duty:dutyList){
				rMap = new HashMap<String, Object>();
				rMap.put("id", duty.getId());
				rMap.put("power", duty.getPower());
				rMap.put("isMain", duty.equals(user.getMainDuty()));
				dutyData.add(rMap);
			}
			model.addAttribute("dutyList", dutyData);
		}
		return "main/company/member_duty_dialog";
	}

	/**
	 * 保存职责信息
	 */
	@RequestMapping(value = "saveDuty", method = RequestMethod.POST)
	@ResponseBody
	public Object saveDuty(@CurrentUser User user, String userId,@RequestParam(value = "powerIds[]") String[] powerIds, String mainPowerId){
		User thisUser = userService.get(userId);
		if(thisUser==null){
			return ajaxJson(resultService.fail("未找到人员信息"));
		}

		//保存主要职责
		Duty mainDuty;
		if(StringUtils.isNotBlank(mainPowerId)){
			Power power = powerService.get(mainPowerId);
			mainDuty = dutyService.getDutyByUserAndPower(thisUser, power);
			if(mainDuty!=null){
				thisUser.setMainDuty(mainDuty);
			}else{
				Duty newDuty = new Duty(thisUser, power);
				dutyService.save(newDuty);
				thisUser.setMainDuty(newDuty);
			}
			userService.update(thisUser);
		}else{
			if(thisUser.getMainDuty()!=null){
				thisUser.setMainDuty(null);
				userService.update(thisUser);
			}
		}


		//保存新职责列表
		List<Power> powerList = new ArrayList<Power>();
		for(String id:powerIds){
			powerList.add(powerService.get(id.trim()));
		}
		return dutyService.saveUserDutyList(thisUser, powerList);
	}

	/**
	 * 修改账号状态
	 */
	@RequestMapping(value = "editAccountEnabled", method = RequestMethod.POST)
	@ResponseBody
	public Object editAccountEnabled(@CurrentUser User user, String val, String userId){
		User doUser = userService.get(userId);
		if(doUser!=null){
			Admin admin = adminService.get(doUser.getAdminId());
			if(admin!=null){
				if(StringUtils.equals("0", val)){ //启用操作
					admin.setAccountEnabled(1);
				}
				if(StringUtils.equals("1", val)){ //禁用操作
					admin.setAccountEnabled(0);
				}
				adminService.update(admin);
				return ajaxJson(resultService.success("操作成功"));
			}
		}
		return ajaxJson(resultService.fail("操作失败"));
	}

	/**
	 * 个人中心页面
	 */
	@RequestMapping(value = "userCenter", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
	public String userCenter(@CurrentUser User user, Model model){
		model.addAttribute("user", user);
		model.addAttribute("admin", adminService.get(user.getAdminId()));
		model.addAttribute("userHeadUrl", userService.getUserHeadUrl(user));
		model.addAttribute("dutyList", dutyService.getUserDutyList(user));
		return "/main/menu/company/userCenter";
	}

	/**
	 * 头像剪裁dialog
	 */
	@RequestMapping(value = "logoDialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
	public String logoDialog(@CurrentUser User user,Model model,  String userId){
		User doUser = userService.get(userId);
		if(doUser==null) doUser = user;
		model.addAttribute("logoUrl", userService.getUserHeadUrl(doUser));
		model.addAttribute("logoName", "head_"+doUser.getName());
		return "/main/company/logo_tailor_dialog";
	}

	/**
	 * 更新个人资料
	 */
	@RequestMapping(value = "updateUserCenter", method = RequestMethod.POST)
	@ResponseBody
	public Object updateUserCenter(@CurrentUser User currentUser, String userId, String headFileId, BaseEnumManager.SexEnum sex, String birthday, String place, String cardId){
		User user = userService.get(userId);
		if(user!=null){
			user.setHeadFileId(headFileId);
			user.setSex(sex);
			user.setBirthday(StrUtil.isNotBlank(birthday) ? DateUtil.parse(birthday, "yyyy-MM-dd") : null);
			user.setCardId(cardId);
			if(StrUtil.isNotBlank(place)){
				String[] placeArr = StrUtil.split(place, "/");
				if(placeArr.length>0){
					user.setProvince(placeArr[0]);
				}
				if(placeArr.length>1){
					user.setCity(placeArr[1]);
				}
				if(placeArr.length>2){
					user.setCounty(placeArr[2]);
				}
			}
			userService.update(user);
			String userHeadUrl = userService.getUserHeadUrl(user);
			return ajaxJson(resultService.successWithData(userHeadUrl));
		}

		return ajaxJson(resultService.fail());
	}

	/**
	 * 个人中心 - 账号绑定修改dialog
	 */
	@RequestMapping(value = "member_account_change_dialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
	public String member_account_change_dialog(@CurrentUser User user, Model model, String type){
		model.addAttribute("user", user);
		model.addAttribute("admin", adminService.get(user.getAdminId()));
		model.addAttribute("type", type);
		return "/main/company/member_account_change_dialog";
	}

	/**
	 * 个人中心 - 账号绑定修改
	 */
	@RequestMapping(value = "updateAccount", method = RequestMethod.POST)
	@ResponseBody
	public Object updateAccount(@CurrentUser User user, String type, String adminId, String username, String userMobile, String userEmail){
		if(StrUtil.isNotBlank(type) && StrUtil.isNotBlank(adminId)){
			Admin admin = adminService.get(adminId);
			if(StrUtil.equals("username", type)){
				return adminService.updateUsername(admin, username);
			}else if(StrUtil.equals("userMobile", type)){
				return adminService.updateUserMobile(admin, userMobile);
			}else if(StrUtil.equals("userEmail", type)){
				return adminService.updateUserEmail(admin, userEmail);
			}
		}
		return ajaxJson(resultService.fail());
	}

	/**
	 * 验证密码是否正确
	 */
	@RequestMapping(value = "validPassword", method = RequestMethod.GET)
	@ResponseBody
	public Object validPassword(@CurrentUser User user, String oldPassword){
		if(adminService.validPassword(adminService.get(user.getAdminId()), oldPassword)){
			return ajaxJson(resultService.success());
		}else{
			return ajaxJson(resultService.fail());
		}
	}

	/**
	 * 修改密码
	 */
	@RequestMapping(value = "updatePassword", method = RequestMethod.POST)
	@ResponseBody
	public Object updatePassword(@CurrentUser User user, String newPassword){
		return ajaxJson(adminService.updatePassword(adminService.get(user.getAdminId()), newPassword));
	}

	/**
	 * 更改主要职责
	 */
	@RequestMapping(value = "updateMainDuty", method = RequestMethod.POST)
	@ResponseBody
	public Object updateMainDuty(@CurrentUser User user, String dutyId){
		if(StrUtil.isNotBlank(dutyId)){
			user.setMainDuty(dutyService.get(dutyId));
			userService.update(user);
			return resultService.success();
		}
		return resultService.fail();
	}


}
